/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lt.ntec.danblog.server.core.model.objectify;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.Query;
import java.util.LinkedList;
import java.util.List;
import lt.ntec.danblog.server.core.model.BaseDAO;
import lt.ntec.danblog.server.core.model.Persistable;

/**
 *
 * @author Tadas Šubonis
 */
public abstract class ObjectifyBaseDAO<T extends Persistable> implements
        BaseDAO<T> {
    
    final protected Objectify ofy;
    
    public ObjectifyBaseDAO(Objectify ofy){
        this.ofy = ofy;
    }
    
    @Override
    public T getById(Long id) {
        return ofy.get(new Key<T>(getEntityClass(), id));
    }

    @Override
    public Long save(T entity) {
        ofy.put(entity);
        return entity.getId();
    }

    @Override
    public void delete(T entity) {
        ofy.delete(entity);
    }

    @Override
    public void delete(Long id) {
        ofy.delete(new Key<T>(getEntityClass(), id));
    }

    @Override
    public List<? extends T> getList() {
        List<T> list = new LinkedList<T>();
        Query<? extends T> q = ofy.query(getEntityClass());
        for (T object : q) {
            list.add(object);
        }
        return list;
    }
    
    public abstract Class<? extends T> getEntityClass();
}
